/**
 *  aside用于在一本书的详细信息被点击后显示书的详细信息，从页面右侧滑入／滑出
 */

import React from 'react';
import { is } from 'immutable';
import { connect } from 'react-redux';
import store from '../../redux/store';
import * as css from './style'
import * as action from '../../redux/action';
import { fetch, fetchDouban, merge, handleError, getStackName } from '../../utils/utils';


class Aside extends React.Component {

    constructor(props) {
        super(props);
        this.handleAction = this.handleAction.bind(this);
    }

    // 只有render内的数据改变后才重新渲染
    shouldComponentUpdate(nextProps) {
        return !is(nextProps.ASIDE_R, this.props.ASIDE_R);
    }

    handleAction(e) {
        e.preventDefault();
        this.props.hideAside();
    }

    render() {
        let render = this.props.ASIDE.render,
            book = render.book,
            douban = render.douban;

        // 页面首次加载时book为undefined
        if (book === undefined) return <div className={ css.panel }></div>;

        /**
         *  当点击另一本书的详细信息时，aside内的豆瓣数据将会于即将显示的书不符，则重
         *  新向豆瓣请求数据，并将数据merge进redux。
         */
        if (book.isbn !== douban.isbn) {
            fetchDouban(book.isbn).done(res => {
                this.props.parseDouban(res.summary, res.alt, book.isbn);
            }).fail(() => {
                this.props.parseDouban(undefined, undefined, book.isbn);
            });
        }

        return (
            <div className={ css.panel }>
                <i className={ css.back } onClick={ this.handleAction }
                    onTouchStart={ this.handleAction }/>

                <div className={ css.title }>{ book.title }</div>

                <BookDesc book={ book } action={ this.props } isLike={ render.isLike }/>

                <Douban data={ douban }/>
            </div>
        )
    }
}


/**
 *  book describe content.
 *  @props book: state.render.book
 *  @props action: redux action
 *  @props isLike: bool, does user like this book.
 */
class BookDesc extends React.Component {

    constructor(props) {
        super(props);
        this.getlike = this.getlike.bind(this);
    }

    getlike(e) {
        e.preventDefault();

        let { book, isLike, action } = this.props;
        let username = store.getState().USER.getIn(['render', 'user']);

        if (!username) {
            action.sendMessage('尚未登录，暂时无法使用该功能。');
            return false;
        } else {
            // 订阅此书
            if (isLike === false) {
                let queryObj = {
                    ctrlid: book.detail,
                    title: book.title,
                    search_id: book.searchId,
                    shuku: getStackName(book.searchId) || ' ',
                    allNum: book.allNum
                };

                fetch(merge(queryObj, {
                    do: 'subscibe',
                    username: username
                })).done(res => {
                    if (res.error === false) {
                        action.addFeedBook(merge(queryObj, { on: book.on }));
                    } else {
                        action.sendMessage(res.msg);
                    }
                }).fail(handleError.bind(this));

            } else {
                // 取消订阅此书
                fetch({
                    do: 'csub',
                    ctrlid: book.detail,
                    username: username
                }).done(res => {
                    if (res.error === false) {
                        action.removeFeedBook(book.detail);
                    } else {
                        action.sendMessage(res.msg);
                    }
                }).fail(handleError.bind(this));
            }

        }
    }

    render() {
        let { book, isLike } = this.props;

        return (
            <div className={ css.block }>
                <Label icon={ css.iconqr } text="上架信息"/>

                <ul>
                    <li>ISBN: { book.isbn }</li>
                    <li>索书号: { book.searchId }</li>
                    <li>长安校区: 共 { book.allNum } 本，{ book.on } 本可借 { `${getStackName(book.searchId)}` }</li>
                    <li>雁塔校区: 0本可借</li>
                </ul>

                <i className={ css.star }
                    title={ isLike ? '取消订阅' : '订阅' }
                    data-islike={ isLike }
                    onClick={ this.getlike }
                    onTouchStart={ this.getlike }></i>
            </div>
        )
    }
}


/**
 *  douabn data
 *  @props data: state.render.douban( get from douban api )
 */
class Douban extends React.Component {
    render() {
        let douban = this.props.data,
            abstract = douban ? this.props.data.summary : undefined,
            link = douban ? this.props.data.link : undefined;

        return (
            <div className={ css.block }>
                <Label icon={ css.iconinfo } text="图书简介"/>
                <p>{ abstract ? abstract : '暂无简介' }</p>
                {
                    link ?
                        <a href={ link } className={ css.dblink } target="_blank">去豆瓣查看更多</a> : ''
                }
            </div>
        )
    }
}


/**
 *  label text
 *  @props icon: string, css class name
 *  @props text: string
 */
class Label extends React.Component {
    render() {
        let icon = this.props.icon,
            text = this.props.text;
        return (
            <div className={ css.label }>
                <i className={ icon }/>{text}
            </div>
        )
    }
}


export default connect(state => ({
    ASIDE: state.ASIDE.toJS(),
    ASIDE_R: state.ASIDE.get('render')
}), action)(Aside);
